import sys, time

from PySide6.QtWidgets import QApplication, QMainWindow, QMessageBox, QFileDialog, QTableWidgetItem, QPushButton
from PySide6.QtGui import QAction
from PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger

from ui.main_ui import Ui_MainWindow
from worker import PreviewWorker, StartWorker
from log import logger


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.about = QAction('关于', self)
        self.ui.menubar.addAction(self.ui.about)
        self.ui.tableWidget.setHorizontalHeaderLabels(['状态', '序号', '页码', '文件名'])

        self.tab = 0
        self.pro_mode = 0
        self.pdf_page = 0
        self.split_pages = []
        self.items = []
        self.preview_worker = PreviewWorker(self)
        self.start_worker = StartWorker(self)

        self.ui.about.triggered.connect(self.smooth_pdf_about)

        self.ui.input_file_button.clicked.connect(self.load_file_path)
        self.ui.output_dir_button.clicked.connect(self.load_dir_path)
        self.ui.comboBox.currentIndexChanged.connect(self.load_mode)

        self.ui.input_files_button.clicked.connect(self.load_files_path)
        self.ui.output_file_button.clicked.connect(self.save_file_path)

        self.ui.preview_button.clicked.connect(self.preview)
        self.ui.start_button.clicked.connect(self.start)

        self.ui.statusbar.showMessage('准备就绪')

    def preview(self):
        self.items.clear()
        self.tab = self.ui.tab_widget.currentIndex()
        try:
            self.get_split_pages()
            self.disable_button(self.ui.preview_button)
            self.preview_worker.done.connect(lambda: self.enable_button(self.ui.preview_button))
            self.preview_worker.start()
        except ValueError:
            QMessageBox.critical(self, '分割参数错误', '请检查分割参数')

    def start(self):
        self.preview()
        self.disable_button(self.ui.start_button)
        self.start_worker.done.connect(lambda: self.enable_button(self.ui.start_button))
        self.start_worker.start()

    def smooth_pdf_about(self):
        logger.info('About')
        QMessageBox.about(self, '关于', '作者：Veoco\n版本：0.2.1\n开源协议：AGPL-3.0')

    def disable_button(self, button: QPushButton):
        button.setEnabled(False)

    def enable_button(self, button: QPushButton):
        button.setEnabled(True)

    def load_file_path(self, multi=False):
        file = QFileDialog.getOpenFileName(self, '选择文件', './', "PDF Files (*.pdf);;All Files (*)")
        logger.debug('Open file {}'.format(file))
        if file[0]:
            filename = file[0]
            logger.info('Open file {}'.format(filename))

            self.ui.input_file.setText(filename)
            pdf_reader = PdfFileReader(filename)
            self.pdf_page = pdf_reader.numPages
            self.ui.statusbar.showMessage('共有{}页'.format(self.pdf_page))

    def load_files_path(self):
        files = QFileDialog.getOpenFileNames(self, "选择多个文件", "./", "PDF Files (*.pdf);;All Files (*)")
        logger.debug('Open file {}'.format(files))
        if files[0]:
            file_names = files[0]
            logger.info('Open files {}'.format(file_names))

            self.ui.input_files.setText(','.join(file_names))
            self.ui.statusbar.showMessage('共有{}个文件'.format(len(file_names)))

    def save_file_path(self):
        file = QFileDialog.getSaveFileName(self, '选择文件', './', "PDF Files (*.pdf);;All Files (*)")
        logger.debug('Open file {}'.format(file))
        if file[0]:
            filename = file[0]
            logger.info('Open file {}'.format(filename))

            self.ui.output_file.setText(filename)

    def load_dir_path(self):
        dir_name = QFileDialog.getExistingDirectory(self, '选择文件夹', './')
        logger.debug('Dir name {}'.format(dir_name))
        if dir_name:
            logger.info('Open dir {}'.format(dir_name))
            self.ui.output_dir.setText(dir_name)

    def load_mode(self):
        self.pro_mode = self.ui.comboBox.currentIndex()
        logger.info(self.pro_mode)
        self.ui.input_info.clear()

    def get_split_pages(self):
        self.split_pages.clear()
        if not self.pro_mode:
            self.get_simple_split_pages()
        else:
            self.get_pro_split_pages()

    def get_simple_split_pages(self):
        info = self.ui.input_info.text()
        if info.isdigit() and 0 < int(info) < self.pdf_page:
            num = int(info)
            self.split_pages = [i * num for i in range(1, self.pdf_page // num + 1)]
        else:
            raise ValueError

    def get_pro_split_pages(self):
        info = self.ui.input_info.text()
        if info:
            nums = info.replace(' ', '').split(',')
            self.split_pages = [int(num) for num in nums]
            self.split_pages.sort()
        else:
            raise ValueError

    def show_table(self):
        self.ui.tableWidget.setRowCount(len(self.items))
        for i, row in enumerate(self.items):
            logger.debug(row)
            status = QTableWidgetItem(row[0])
            order = QTableWidgetItem(str(row[1]))
            page = QTableWidgetItem('{}-{}'.format(row[2][0], row[2][1]))
            name = QTableWidgetItem(row[3])
            self.ui.tableWidget.setItem(i, 0, status)
            self.ui.tableWidget.setItem(i, 1, order)
            self.ui.tableWidget.setItem(i, 2, page)
            self.ui.tableWidget.setItem(i, 3, name)
        self.ui.statusbar.showMessage('将生成{}个文件'.format(len(self.items) or 1))

    def preview_split(self):
        file_path = self.ui.input_file.text()
        dir_path = self.ui.output_dir.text()
        file_name = file_path.split('/')[-1]

        start = 1
        order = 1
        for order, end in enumerate(self.split_pages):
            row = ('就绪', order + 1, (start, end), "{}/{}-{}".format(dir_path, order + 1, file_name))
            self.items.append(row)
            start = end + 1
        self.items.append(('就绪', order + 2, (start, self.pdf_page), "{}/{}-{}".format(dir_path, order + 2, file_name)))

        self.show_table()

    def preview_merge(self):
        file_names = self.ui.input_files.text().split(',')
        name = self.ui.output_file.text()

        count = 0
        for filename in file_names:
            pdf_reader = PdfFileReader(filename)
            count = count + pdf_reader.getNumPages()

        self.items.append(('就绪', 1, (1, count), name))

        self.show_table()

    def start_split(self):
        file_name = self.ui.input_file.text()
        dir_name = self.ui.output_dir.text()
        pdf_reader = PdfFileReader(file_name)

        for i, row in enumerate(self.items):
            self.ui.tableWidget.setItem(i, 0, QTableWidgetItem('进行中'))
            pdf_writer = PdfFileWriter()
            for page_num in range(row[2][0] - 1, row[2][1]):
                page_obj = pdf_reader.getPage(page_num)
                pdf_writer.addPage(page_obj)

            with open(row[3], 'wb') as f:
                pdf_writer.write(f)
            self.ui.tableWidget.setItem(i, 0, QTableWidgetItem('完成'))

    def start_merge(self):
        file_names = self.ui.input_files.text().split(',')
        name = self.ui.output_file.text()
        pdf_merger = PdfFileMerger()
        self.ui.tableWidget.setItem(0, 0, QTableWidgetItem('进行中'))
        for filename in file_names:
            pdf_merger.append(filename)
        pdf_merger.write(name)
        self.ui.tableWidget.setItem(0, 0, QTableWidgetItem('完成'))
        self.ui.statusbar.showMessage('已生成{}个文件'.format(1))


if __name__ == "__main__":
    # logger.setLevel('DEBUG')
    logger.info('Start app')
    app = QApplication(sys.argv)

    logger.info('Start MainWindow')
    window = MainWindow()
    window.show()

    sys.exit(app.exec())
